package fetcher;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

public class DownloadFromMQ {
	private ConnectionFactory factory;
	private Destination queue;
	private Connection con;
	private Session session;
	private MessageConsumer consumer;
	
	public DownloadFromMQ() throws JMSException{
		factory = new ActiveMQConnectionFactory("tcp://10.222.29.178:61616");
		queue = new ActiveMQQueue("books");
		con = factory.createConnection();
		con.start();
		
		session = con.createSession(true, Session.AUTO_ACKNOWLEDGE);
		consumer = session.createConsumer(queue);
	}
	
	/**
	 * receive the strings from MQ, 1000 msg one time
	 * @return msg in array
	 */
	public String[] receive() {
		
		String[] strings = new String[1000];
		for(int i=0; i<1000; i++){
			TextMessage msg;
			try {
				msg = (TextMessage) consumer.receive();
				strings[i] = msg.getText();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		return strings;
	}
	
	public void commit() throws JMSException{
		session.commit();
	}
	
	public void close(){
		try {
			consumer.close();
			session.close();
			con.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}

}
